<template>
  <a-modal v-model:open="visible" title="添加用户" width="800px" :confirm-loading="loading" :mask-closable="false" @ok="handleSubmit" @cancel="handleCancel">
    <div class="add-user-form">
      <a-form ref="formRef" :model="formData" :rules="rules" layout="vertical" :label-col="{ span: 24 }" :wrapper-col="{ span: 24 }">
        <!-- 头像上传区域 -->
        <div class="avatar-section">
          <div class="avatar-upload">
            <UploadPic accept=".png,.jpg,.jpeg,gif" :value="formData.avatar" text="上传头像" @change="changePic" />
          </div>
        </div>

        <!-- 基本信息 -->
        <div class="form-section">
          <h3 class="section-title">
            <UserOutlined />
            基本信息
          </h3>
          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="账号" name="account" required>
                <a-input v-model:value="formData.account" placeholder="请输入账号" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="昵称" name="nickName" required>
                <a-input v-model:value="formData.nickName" placeholder="请输入昵称" />
              </a-form-item>
            </a-col>
          </a-row>

          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="性别" name="gender" required>
                <a-select v-model:value="formData.gender" placeholder="请选择性别" :options="genderOptions" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="手机号" name="phone" required>
                <a-input v-model:value="formData.phone" max-length="11" placeholder="请输入手机号" />
              </a-form-item>
            </a-col>
          </a-row>

          <a-form-item label="邮箱" name="email" required>
            <a-input v-model:value="formData.email" placeholder="请输入邮箱地址" />
          </a-form-item>
        </div>

        <!-- 安全设置 -->
        <div class="form-section">
          <h3 class="section-title">
            <LockOutlined />
            安全设置
          </h3>
          <a-row :gutter="16">
            <a-col :span="24">
              <a-form-item :label="formData.id ? '重置密码' : '密码'" name="password" :required="formData.id ? false : true">
                <a-input v-if="formData.id" v-model:value="formData.password" placeholder="重置密码(不更改无需填写)" size="large" />
                <a-input v-else v-model:value="formData.password" placeholder="请输入密码" />
              </a-form-item>
            </a-col>
          </a-row>
        </div>

        <!-- 权限设置 -->
        <div class="form-section">
          <h3 class="section-title">
            <TeamOutlined />
            权限设置
          </h3>
          <a-form-item label="用户角色" name="roles" required>
            <a-select v-model:value="formData.roles" mode="multiple" placeholder="请选择用户角色" :options="roleOptions" />
          </a-form-item>

          <a-form-item label="账户状态" name="status">
            <a-radio-group v-model:value="formData.status">
              <a-radio-button :value="0">
                <CheckCircleOutlined />
                启用
              </a-radio-button>
              <a-radio-button :value="1">
                <StopOutlined />
                禁用
              </a-radio-button>
            </a-radio-group>
          </a-form-item>
        </div>
      </a-form>
    </div>
  </a-modal>
</template>

<script setup>
import UploadPic from '@/components/UploadPic/index.vue'
import { CheckCircleOutlined, LockOutlined, StopOutlined, TeamOutlined, UserOutlined } from '@ant-design/icons-vue'

const props = defineProps({
  open: {
    type: Boolean,
    default: false,
  },
})

const emit = defineEmits(['update:open', 'success'])

const visible = computed({
  get: () => props.open,
  set: val => emit('update:open', val),
})

const formRef = ref()
const loading = ref(false)
const fileList = ref([])

// 表单数据
const formData = reactive({
  account: '',
  nickName: '',
  gender: null,
  phone: '',
  email: '',
  password: '',
  avatar: '',
  roles: [],
  status: 0,
})

// 性别选项
const genderOptions = [
  { label: '男', value: 1 },
  { label: '女', value: 0 },
]

// 角色选项
const roleOptions = ref([]) // 这里可以从API获取角色列表

// 表单验证规则
const rules = {
  account: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { min: 3, max: 20, message: '账号长度在 3 到 20 个字符', trigger: 'blur' },
    { pattern: /^\w+$/, message: '账号只能包含字母、数字和下划线', trigger: 'blur' },
  ],
  nickName: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 10, message: '昵称长度在 2 到 10 个字符', trigger: 'blur' },
  ],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' },
  ],
  email: [
    { required: false, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' },
  ],
  roles: [
    { required: true, message: '至少需要有一个角色', trigger: 'blur' },
  ],
}

function changePic({ url }) {
  formData.avatar = url
}

// 提交表单
async function handleSubmit() {
  try {
    await formRef.value.validate()
    loading.value = true
    const formDataCopy = { ...formData }
    formDataCopy.roles = []
    roleOptions.value.forEach(role => {
      if (formData.roles.includes(role.value)) {
        formDataCopy.roles.push({ roleId: role.value, roleName: role.label })
      }
    })
    const apiUrl = formData.id ? '/admin/user/update' : '/admin/user/add'
    // 这里调用API创建用户
    await httpRequest(apiUrl, formDataCopy)
    message.success(`${formData.id ? '编辑' : '创建'}用户成功!`)
    emit('success')
    handleCancel()
  }
  catch (error) {
    loading.value = false
  }
}

// 取消操作
function handleCancel() {
  formRef.value?.resetFields()
  Object.assign(formData, {
    id: null,
    account: '',
    nickName: '',
    gender: '',
    phone: '',
    email: '',
    password: '',
    avatar: '',
    roles: [],
    status: 'active',
  })
  fileList.value = []
  rules.password = [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' },
  ]
  loading.value = false
  visible.value = false
}

function edit(user) {
  Object.assign(formData, user)
  visible.value = true
  rules.password = [
    { required: false, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' },
  ]
  httpRequest('/admin/user/roles', { id: user.id }).then(data => {
    formData.roles = data.map(role => role.roleId)
  })
}

// 获取角色列表
httpRequest('/admin/role/all', {}).then(data => (roleOptions.value = data))

defineExpose({ edit })
</script>

<style lang="less" scoped>
.add-user-form {
  box-sizing: border-box;
  width: 100%;
  max-height: 70vh;
  padding: 0 4px;
  overflow-y: auto;

  .avatar-section {
    display: flex;
    justify-content: center;
    padding: 24px;
    margin-bottom: 32px;
    background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
    border-radius: 12px;

    .avatar-upload {
      width: 120px;
      height: 120px;
      overflow: hidden;
      border: 3px dashed #d9d9d9;
      border-radius: 50%;
    }
  }

  .form-section {
    margin-bottom: 32px;

    .section-title {
      display: flex;
      align-items: center;
      padding-bottom: 8px;
      margin-bottom: 20px;
      font-size: 16px;
      font-weight: 600;
      color: #262626;
      border-bottom: 2px solid #f0f0f0;

      .anticon {
        margin-right: 8px;
        font-size: 18px;
        color: #1890ff;
      }
    }
  }

  :deep(.ant-form-item-label > label) {
    font-weight: 500;
    color: #595959;
  }

  :deep(.ant-input-affix-wrapper) {
    border-radius: 8px;
    transition: all 0.3s ease;

    &:hover,
    &:focus-within {
      border-color: #1890ff;
      box-shadow: 0 0 0 2px rgb(24 144 255 / 10%);
    }
  }

  :deep(.ant-select) {
    .ant-select-selector {
      border-radius: 8px;
      transition: all 0.3s ease;

      &:hover,
      &:focus {
        border-color: #1890ff;
        box-shadow: 0 0 0 2px rgb(24 144 255 / 10%);
      }
    }
  }

  :deep(.ant-radio-group) {
    .ant-radio-button-wrapper {
      &.ant-radio-button-wrapper-checked {
        color: white;
        background: #1890ff;
        border-color: #1890ff;
        box-shadow: 0 2px 8px rgb(24 144 255 / 30%);
      }
    }
  }
}

// 滚动条样式
.add-user-form::-webkit-scrollbar {
  width: 0;
}

.add-user-form::-webkit-scrollbar-track {
  background: #fff;
  border-radius: 3px;
}

.add-user-form::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;

  &:hover {
    background: #a8a8a8;
  }
}
</style>
